/**
 * @author 雷明浩
 * @date 2025/6/3 11:39
 */
public class ReverseKGroup {
    // newcoder 链表中的每个节点每k个一组翻转
    // https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e?tpId=295&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj%3FquestionJobId%3D10%26subTabName%3Donline_coding_page
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        if (head == null || head.next == null) {
            return head;
        }
        ListNode  cur = head;
        for (int i = 0; i < k; i++) {
            cur = cur.next;
            if (cur == null && i != k-1) {
                return head;
            }
        }
        ListNode nextList = reverseKGroup(cur, k);
        ListNode prev = nextList;
        cur = head;
        for (int i = 0; i < k; i++) {
            ListNode curNext = cur.next;
            cur.next = prev;
            prev = cur;
            cur = curNext;
        }
        return prev;
    }
}